//
//  HYSettingViewController.m
//  XPlayer
//
//  Created by 张水 on 2023/9/11.
//

#import "HYSettingViewController.h"
#import "HYSettingCell.h"
#import "HYSettingHeadView.h"
#import "HYAboutUsViewController.h"
#import "HYAlertActionView.h"
#import "HYFileDownloadViewController.h"
#import <HYUIKit/HYPopMenu.h>
#import "HYLanguageModel.h"
#import "NSBundle+Language.h"
#import "CYLTabBarControllerConfig.h"
#import "HYAlertShowView.h"
#import "HYAlertView.h"
#import "HYCustomAlertView.h"
#import "HYPayManager.h"

@interface HYSettingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) NSArray *dataSource;

@property (nonatomic, strong) NSArray *localLanguages;

@end

@implementation HYSettingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = NSLocalizedString(@"设置", nil);
    self.view.backgroundColor = AppBgThemeColor;
    self.navigationBarView.navagationBarStyle = None_button_show;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.navigationBarView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
    self.dataSource = [HYSettingDataSource settingArray];
    [self addRefreshListNotify];
}

- (void)addRefreshListNotify
{
    [kNotificationCenter addObserver:self selector:@selector(refreshList) name:kSetRefreshListNotification object:nil];
}

- (void)refreshList
{
    [self.tableView reloadData];
}

#pragma mark UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [self.dataSource objectAtIndex:section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELLIDHYSettingCell" forIndexPath:indexPath];
    NSArray *array = [self.dataSource objectAtIndex:indexPath.section];
    HYSettingModel *model = [array objectAtIndex:indexPath.row];
    [cell setData:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [self.dataSource objectAtIndex:indexPath.section];
    HYSettingModel *model = [array objectAtIndex:indexPath.row];
    if (model.dataID == kPlayStyle) {
        //todo 播放类型
    }
    if (model.dataID == kChangeLanguage) {
        // 切换语言
        [self showLanuageAlert];
    }
    if (model.dataID == kChangeTheme) {
        // 切换语言
        [self showThemeAlertWithIndexPath:indexPath];
    }
    if(model.dataID == kMineDownload) {
        // 视频下载
        [self jumpMineDownload];
    }
    
    if (model.dataID == kClearMemory) {
        //清除APP缓存
        [HYAlertActionView showViewControler:self title:NSLocalizedString(@"温馨提示", nil) message:NSLocalizedString(@"清除缓存后数据无法恢复，请谨慎操作！", nil) actionTitle:@[NSLocalizedString(@"确定", nil),NSLocalizedString(@"取消", nil)] sureBlock:^{
            [HYMineSetManager clearAppCache];
        } cancelBlock:nil];
    }
    
    if (model.dataID == kFeedback) {
        NSURL* url = [self QQQunUrl];
        if ([[UIApplication sharedApplication] canOpenURL:url]){
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:^(BOOL success) {
                }];
            }
        } else {
            [HYHub showMessage:NSLocalizedString(@"没有安装QQ", nil) delay:3];
        }
    }
    
    if (model.dataID == kGoodReview) {
        [self goodReview];
    }
    
    if (model.dataID == kGivePrize){
        [self givePrize];
    }
    
    if (model.dataID == kAboutUs) {
        [self jumpAboutUs];
    }
}

#pragma mark - 切换语言
- (void)showLanuageAlert
{
    @weakify(self);
    __block NSArray *actionTitles = @[NSLocalizedString(@"中文简体",nil),NSLocalizedString(@"中文繁体",nil),NSLocalizedString(@"英语",nil),NSLocalizedString(@"日语",nil),NSLocalizedString(@"韩语",nil)];
    HYCustomAlertView *alertView = [[HYCustomAlertView alloc]initWithHeaderTitle:NSLocalizedString(@"切换语言", nil) actionTitles:actionTitles actionBlock:^(NSNumber *resultNumber) {
        @strongify(self);
        [self changeLanuage:actionTitles[[resultNumber integerValue]]];
    }];
    [alertView show];
}

- (void)changeLanuage:(NSString *)lanuage
{
    __block HYLanguageModel *model;
    [self.localLanguages enumerateObjectsUsingBlock:^(HYLanguageModel *tempModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if([tempModel.showTitle isEqualToString:lanuage]){
            model = tempModel;
            *stop = YES;
        }
    }];
    HYLanguageManager.currentLanguage = model.localizable;
    //创建新的UITabbarController
    CYLTabBarControllerConfig *tabBarControllerConfig = [[CYLTabBarControllerConfig alloc] init];
    CYLTabBarController *tabBarController = tabBarControllerConfig.tabBarController;
    //找到对应的nav
    tabBarController.selectedIndex = 2;
    //主线程刷新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].delegate.window.rootViewController = tabBarController;
    });
}

- (NSArray *)localLanguages
{
    if(!_localLanguages){
        NSArray *availableLanguages = [[NSBundle mainBundle] localizations];
        NSMutableArray *tmpArray = [NSMutableArray array];
        for (int i = 0; i < availableLanguages.count; i++) {
            //取出来的都是zh-Hans-CN 这样的 要转一下
            NSString *localizableString = availableLanguages[i];
            if ([localizableString isEqualToString:@"Base"]) {
                continue;
            }
            HYLanguageModel *model = [[HYLanguageModel alloc]init];
            model.showTitle = [self localizableToString:localizableString];
            model.localizable = localizableString;
            [tmpArray addObject:model];
        }
        
        _localLanguages = [tmpArray copy];
    }
    return  _localLanguages;
}

- (NSString *)localizableToString:(NSString *)language
{
    NSString *string;
    if ([language containsString:@"zh-Hans"] || [language containsString:@"zh_CN"]) {
        string = NSLocalizedString(@"中文简体",nil);
    }
    if ([language containsString:@"ko"]) {
        string = NSLocalizedString(@"韩语",nil);
    }
    if ([language containsString:@"ja"]) {
        string = NSLocalizedString(@"日语",nil);
    } 
    if ([language containsString:@"en"]) {
        string = NSLocalizedString(@"英语",nil);
    }
    if ([language containsString:@"zh-Hant"] || [language containsString:@"zh_TW"]) {
        string = NSLocalizedString(@"中文繁体",nil);
    }
    if ([language containsString:@"Base"]) {
        string = NSLocalizedString(@"系统默认",nil);
    }
    return string;
}

#pragma mark - 切换主题
- (void)showThemeAlertWithIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    __block NSArray *actionTitles = @[NSLocalizedString(@"浅色主题",nil),NSLocalizedString(@"深色主题",nil),NSLocalizedString(@"自动跟随",nil)];
    HYCustomAlertView *alertView = [[HYCustomAlertView alloc]initWithHeaderTitle:NSLocalizedString(@"切换主题", nil) actionTitles:actionTitles actionBlock:^(NSNumber *resultNumber) {
        @strongify(self);
        [self changeTheme:[resultNumber integerValue] IndexPath:indexPath];
    }];
    [alertView show];
}

- (void)changeTheme:(NSInteger)index IndexPath:(NSIndexPath *)indexPath
{
    if (@available(iOS 13.0, *)) {
        if(index == 0){
            [HYMineSetManager shareManager].appThemeMode = UIUserInterfaceStyleLight;
        }else if (index == 1){
            [HYMineSetManager shareManager].appThemeMode = UIUserInterfaceStyleDark;
        }else{
            [HYMineSetManager shareManager].appThemeMode = UIUserInterfaceStyleUnspecified;
        }
    }
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)goodReview
{
    NSString *APPID = @"6473444511";
    NSString *urlString = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",APPID];
    NSURL *url = [NSURL URLWithString:urlString];
    [[UIApplication sharedApplication]openURL:url options:@{UIApplicationOpenURLOptionsSourceApplicationKey:@YES} completionHandler:^(BOOL success) {
    }];
}

- (void)givePrize
{
    @weakify(self);
    __block NSArray *actionTitles = @[NSLocalizedString(@"一瓶矿泉水💧",nil),NSLocalizedString(@"一瓶饮料🥤",nil),NSLocalizedString(@"一杯咖啡☕️",nil),NSLocalizedString(@"一个鸡腿🍗",nil),NSLocalizedString(@"一个汉堡🍔",nil)];
    HYCustomAlertView *alertView = [[HYCustomAlertView alloc]initWithHeaderTitle:NSLocalizedString(@"鼓励支持", nil) actionTitles:actionTitles actionBlock:^(NSNumber *resultNumber) {
        @strongify(self);
        [self userPrizeSupportWithSelectIndex:[resultNumber integerValue]];
    }];
    [alertView show];
}

- (void)userPrizeSupportWithSelectIndex:(NSInteger)index
{
    [[HYPayManager shareManager] requestApplePayWithSelectIndex:index respBlock:^(BOOL paySuccess) {
        [HYPayManager releaseManager];
    }];
}

#pragma mark - UITableViewDelegate && UITableDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HYSettingHeadView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"CELLIDHYSettingHeadView"];
    if (section == 0) {
        [headView setHeadTitle:NSLocalizedString(@"通用设置", nil) withTextAlignment:NSTextAlignmentLeft];
    }
    if (section == 1) {
        [headView setHeadTitle:NSLocalizedString(@"离线缓存", nil) withTextAlignment:NSTextAlignmentLeft];
    }
    if (section == 2) {
        [headView setHeadTitle:NSLocalizedString(@"播放设置", nil) withTextAlignment:NSTextAlignmentLeft];
    }
    if (section == 3) {
        [headView setHeadTitle:NSLocalizedString(@"其他", nil) withTextAlignment:NSTextAlignmentLeft];
    }
    return headView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (void)clickSwitchAction:(HYSettingModel *)model with:(BOOL)able
{
    
}

- (void)jumpMineDownload
{
    HYFileDownloadViewController *downloadVC = [[HYFileDownloadViewController alloc]init];
    [self.navigationController pushViewController:downloadVC animated:YES];
}

- (void)jumpAboutUs
{
    HYAboutUsViewController *aboutUsVC = [[HYAboutUsViewController alloc]init];
    [self.navigationController pushViewController:aboutUsVC animated:YES];
}

- (NSURL*)QQQunUrl
{
    NSString *qqQunNumber = @"604045934";
    NSString* urlStr = [NSString stringWithFormat:@"mqqapi://card/show_pslcard?src_type=internal&version=1&uin=%@&card_type=group&source=external", qqQunNumber];
    return [NSURL URLWithString:urlStr];
}

#pragma mark getter
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = AppBgThemeColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 45.0;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[HYSettingCell class] forCellReuseIdentifier:@"CELLIDHYSettingCell"];
        [_tableView registerClass:[HYSettingHeadView class] forHeaderFooterViewReuseIdentifier:@"CELLIDHYSettingHeadView"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableView;
}


@end
